<?php
namespace App\Http\Controllers\Business\Shop\V1\Account;

use App\Http\Controllers\Business\Admin\Salesman\ShopSalesmanManagement;
use App\Models\Order;
use App\Models\ShopAccount;
use App\Models\Shop;
use App\Models\ShopSalesman;
use App\Models\ShopSalesmanDetail;
use App\Models\ShopSalesmanWithdrawal;
use Illuminate\Support\Facades\DB;

class Account{
    //首页
    public static function index($shopid,$starttime,$lasttime)
    {
        if(!$shopid || !$starttime || !$lasttime)
        {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data['notaccount'] = Order::where('shopid',$shopid)->where('accountstatus','0')->where('refundstatus', 0)->sum('accountamount');
        if($data['notaccount'] == '') {
            $data['notaccount'] = '0.0';
        }
        //$data['isaccount'] = ShopAccount::where('shopid',$shopid)->sum('accountamount');//需求去掉累计已结款总金额
        $data['isaccount'] = '';
        if($data['isaccount'] == '') {
            $data['isaccount'] = '0.0';
        }
        $data['accountlist'] = ShopAccount::where('shopid',$shopid)->where('accounttime','>=',$starttime.' 00:00:00')
            ->where('accounttime','<=',$lasttime.' 23:59:59')->select(DB::raw("DATE_FORMAT(accounttime,'%Y-%m-%d') accounttime,accountamount"))->orderBy('accounttime','desc')->paginate(20);
        //返回已打款的总笔数和总金额
        $data['accountcount'] = ShopAccount::where('shopid',$shopid)->where('accounttime','>=',$starttime.' 00:00:00')
            ->where('accounttime','<=',$lasttime.' 23:59:59')->count();
        $data['accountsum'] = ShopAccount::where('shopid',$shopid)->where('accounttime','>=',$starttime.' 00:00:00')
            ->where('accounttime','<=',$lasttime.' 23:59:59')->sum('accountamount');
        $data['accountsum'] = isset($data['accountsum']) && !empty($data['accountsum'])?$data['accountsum'] : '0.00';
        return ['status'=>'success','data'=>$data];
    }
    //待结款
    public static function waitList($shopid) {
        if(!$shopid) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $accountstatus = '0';
        $data = Order::where('shopid',$shopid)->where('accountstatus',$accountstatus)->where('refundstatus', 0)
            ->select('ordernumber','shopamount','created_at','accountamount')->orderBy('updated_at', 'desc')->paginate(20);
        return ['status'=>'success','data'=>$data];
    }
    //已结款
    public static function receiptList($shopid) {
        if(!$shopid) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data = ShopAccount::where('shopid',$shopid)->select('accounttime','accountamount')->orderBy('accounttime','desc')->paginate(20);
        return ['status'=>'success','data'=>$data];
    }
    //通过时间来获取已结款的订单列表
    public static function orderListByDate($shopid, $mydate) {
        if(!$shopid || !$mydate) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $previousPlayMoneyDate = ShopAccount::where('shopid',$shopid)->where('accounttime','<',$mydate.' 00:00:00')->orderBy('accounttime','desc')->pluck('accounttime')->first();
        if(!$previousPlayMoneyDate){
            $data = Order::where('shopid',$shopid)->where('accountstatus','1')->where('accounttime', '<=', $mydate. " 23:59:59")->where('refundstatus', 0)
                ->select('ordernumber','shopamount','created_at','accountamount')->paginate(20);
        }else{
            $data = Order::where('shopid',$shopid)->where('accountstatus','1')->where('accounttime', '<=', $mydate. " 23:59:59")->where('refundstatus', 0)
                ->where('accounttime', '>', $previousPlayMoneyDate)->select('ordernumber','shopamount','created_at','accountamount')->paginate(20);
        }
        return ['status'=>'success', 'data'=>$data ];
    }
    public static function orderDetails($shopid,$ordernumber){
        if(!$shopid || !$ordernumber) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $data = Order::where('orders.shopid',$shopid)->where('orders.ordernumber',$ordernumber)
            ->join('shop_users','shop_users.id','=','orders.shopuserid')
            ->select('orders.ordernumber','orders.nickname','orders.shopamount','orders.created_at','orders.shopuserid','shop_users.name as shopusername','orders.accountstatus as `余额支付`')->first();
        return ['status'=>'success','data'=>$data];
    }

    public static function getBankCard($shopid) {
        if(!$shopid) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $data = Shop::where('id', $shopid)->select('bankcard', 'cardholder', 'bankname', 'bankprovince', 'bankcity', 'opencardbank')->first();
        if(isset($data['cardholder'])) {
            $data['cardholder'] = str_replace(mb_substr($data['cardholder'], 0, 1, 'utf-8'), '*', $data['cardholder']);
            $data['opencardbank'] = $data['bankprovince'] .$data['bankcity']. $data['opencardbank'];
        }
        return ['status'=>'success', 'data'=>$data];
    }

    //地推结款
    public static function salesmanIndex($shopId, $page,$perpage=20) {
        if(!$shopId || !$page) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $skip = ($page-1)*$perpage;
        $shopSalesman = ShopSalesman::where('shopid', $shopId)->select('balance', 'type')->first();
        if($shopSalesman) {
            $balance = $shopSalesman['balance'];
            $type = $shopSalesman['type'];
        } else {
            $balance = 0.00;
            $type = '';
        }
        //累计待结款
//        $waitWithdrawalAmount = ShopSalesmanWithdrawal::where('shopid', $shopId)->where('status', 0)->sum('accountamount');
//        if($waitWithdrawalAmount == '') {
//            $waitWithdrawalAmount = 0.00;
//        }
        $lists = ShopSalesmanWithdrawal::where('shopid', $shopId)->where('status', 1)
            ->select(DB::Raw("DATE_FORMAT(accounttime,'%Y-%m-%d') accounttime,accountamount,remark"))
            ->skip($skip)->take($perpage)->get();
        $count = ShopSalesmanWithdrawal::where('shopid', $shopId)->where('status', 1)->count();
        $sum = ShopSalesmanWithdrawal::where('shopid', $shopId)->where('status', 1)->sum('accountamount');
        if($sum == '') {
            $sum = 0;
        }
        $data = [
            'type' => $type,
            'balance' => $balance,
            'count' => $count,
            'sum' => $sum,
            'lists' => $lists,
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //地推待提现
    public static function salesmanWaitWithdrawalList($shopId, $page=1, $perpage=20) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $lists = [];
        $first = ($page - 1) * $perpage;
        $last = $page * $perpage;
        for($i=$first; $i<$last; $i++) {
            $day = date('Y-m-d', strtotime('-' . $i . "days"));
            $dayStartTime = $day. " 00:00:00";
            $dayEndTime = $day. " 23:59:59";
            $registerNum = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->where('type', 'register')->count();
            $validOrderNum = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->where('type', 'order')->count();
            $sumOrderAmount = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->where('type', 'order')->sum('orderamount');
            $sumOrderAmount = ($sumOrderAmount != '') ? $sumOrderAmount:0;
            if(($registerNum != 0) || ($validOrderNum != 0)) {
                $getMoney = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->sum('getmoney');
                $list = [
                    'date' => $day,
                    'registernum' => $registerNum,
                    'ordernum' => $validOrderNum,
                    'orderamount' => $sumOrderAmount,
                    'getmoney' => $getMoney,
                ];
                array_push($lists, $list);
            }
        }
        return ['status'=>'success', 'data'=>$lists];
    }
    //地推待提现 v2版本 2017-03-27
    public static function salesmanWaitWithdrawalListByV2Version($shopId, $page=1, $perpage=20) {
        if(!$shopId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $lists = [];
        $first = ($page - 1) * $perpage;
        $last = $page * $perpage;
        for($i=$first; $i<$last; $i++) {
            $day = date('Y-m-d', strtotime('-' . $i . "days"));
            $dayStartTime = $day. " 00:00:00";
            $dayEndTime = $day. " 23:59:59";
            $registerNum = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->where('type', 'register')->count();
            $validOrderNum = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->where('type', 'order')->count();
            $sumOrderAmount = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->where('type', 'order')->sum('orderamount');
            $sumOrderAmount = ($sumOrderAmount != '')?$sumOrderAmount:0;
            if(($registerNum != 0) || ($validOrderNum != 0)) {
                $getMoney = ShopSalesmanDetail::where('shopid', $shopId)->where('getmoney', '<>', 0)->where('created_at', '>=', $dayStartTime)->where('created_at', '<=', $dayEndTime)->sum('getmoney');
                $list = [
                    'date' => $day,
                    'registernum' => $registerNum,
                    'ordernum' => $validOrderNum,
                    'orderamount' => $sumOrderAmount,
                    'getmoney' => $getMoney,
                ];
                array_push($lists, $list);
            }
        }
        $data = [
            'lists' => $lists,
            'count' => count($lists),
        ];
        return ['status'=>'success', 'data'=>$data];
    }
    //地推结算方式
    public static function salesmanPayMethod($shopId){
        if (!$shopId) {
            return ['status' => 'failed', 'message' => '参数错误'];
        }
        $data = Shop::where('id', $shopId)->select('cardholder', 'bankname', 'bankcard', 'bankprovince', 'bankcity', 'opencardbank')->first();
        if ($data['cardholder']) {
            $data['cardholder'] = str_replace(mb_substr($data['cardholder'], 0, 1, 'utf-8'), '*', $data['cardholder']);
        }
        $type = ShopSalesman::where('shopid', $shopId)->pluck('type')->first();
        if ($type == 'common') {
            $data['accountinterval'] = "当前门店为普通地推商家，每月结算一次，自动打款至收款帐号。";
        } elseif ($type == 'partner') {
            $data['accountinterval'] = "当前门店为地推合伙人商家，每三月结算一次，自动打款至收款帐号。";
        } else {
            $data['accountinterval'] = "";
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //地推已提现
    public static function salesmanWithdrawalList($shopId, $date, $page, $perpage=20) {
        if(!$shopId || !$date) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $skip = ($page-1) * $perpage;
//        $data = ShopSalesmanWithdrawal::where('shopid', $shopId)
//            ->orderBy('created_at', 'desc')
//            ->select('accounttime', 'accountamount','remark')
//            ->skip($skip)->take($perpage)->get();
//        foreach($data as $k => $v) {
//            $yearMonth = date('Y-m', strtotime($data[$k]['accounttime']));
//            $firstDay = date('Y-m-01', strtotime($yearMonth)) . " 00:00:00";
//            $lastDay = date('Y-m-d', strtotime("$yearMonth +1 month -1 day")) . " 23:59:59";
//            $data[$k]['registernum'] = ShopSalesmanDetail::where('shopid', $shopId)->where('type', 'register')
//                ->where('created_at', '>=', $firstDay)->where('created_at', '<=', $lastDay)->count();
//            $data[$k]['validordernum'] = ShopSalesmanDetail::where('shopid', $shopId)->where('type', 'order')
//                ->where('created_at', '>=', $firstDay)->where('created_at', '<=', $lastDay)->count();
//            $orderAmount = ShopSalesmanDetail::where('shopid', $shopId)->where('type', 'order')
//                ->where('created_at', '>=', $firstDay)->where('created_at', '<=', $lastDay)->sum('orderamount');
//            $data[$k]['orderamount'] = ($orderAmount != '') ? $orderAmount : 0;
//        }
//        return ['status'=>'success', 'data'=>$data];
        //判断上次打款时间是否有，没有就取shop_salesman中updated_at的时间  ->pluck('accounttime')->orderBy('accounttime','desc')
        $previousPlayMoneyDate = ShopSalesmanWithdrawal::where('shopid',$shopId)->where('accounttime','<',$date.' 00:00:00')->orderBy('accounttime','desc')->pluck('accounttime')->first();
        if(!empty($previousPlayMoneyDate)){
            $mydate = $previousPlayMoneyDate;
        }else{
            $mydate = ShopSalesman::where('shopid',$shopId)->pluck('created_at')->first();
            $mydate = date("Y-m-d",strtotime($mydate)).' 00:00:00';
        }
        $data = ShopSalesmanWithdrawal::where('accounttime','<=',$date.' 23:59:59')
            ->where('shopid',$shopId)
            ->where('accounttime','>',$mydate)
            ->select(DB::Raw("DATE_FORMAT(accounttime,'%Y-%m-%d') as accounttime,sum(accountamount) as accountamount,remark"))
            ->groupBy("accounttime")
            ->orderBy("accounttime","desc")
            ->skip($skip)
            ->take($perpage)
            ->get();
        foreach($data as $k => $v) {
            $yearMonth = date('Y-m', strtotime($data[$k]['accounttime']));
            $firstDay = date('Y-m-01', strtotime($yearMonth)) . " 00:00:00";
            $lastDay = date('Y-m-d', strtotime("$yearMonth +1 month -1 day")) . " 23:59:59";
            $data[$k]['registernum'] = ShopSalesmanDetail::where('shopid', $shopId)->where('type', 'register')
                ->where('created_at', '>=', $firstDay)->where('created_at', '<=', $lastDay)->count();
            $data[$k]['validordernum'] = ShopSalesmanDetail::where('shopid', $shopId)->where('type', 'order')
                ->where('created_at', '>=', $firstDay)->where('created_at', '<=', $lastDay)->count();
            $orderAmount = ShopSalesmanDetail::where('shopid', $shopId)->where('type', 'order')
                ->where('created_at', '>=', $firstDay)->where('created_at', '<=', $lastDay)->sum('orderamount');
            $data[$k]['orderamount'] = ($orderAmount != '') ? $orderAmount : 0;
        }
        return ['status'=>'success', 'data'=>$data];
    }
}